package com.cskaoyan.service.impl;

import com.cskaoyan.bean.data.PageData;
import com.cskaoyan.mapper.MarketFootprintMapper;
import com.cskaoyan.model.MarketFootprint;
import com.cskaoyan.model.MarketFootprintExample;
import com.cskaoyan.model.MarketGoods;
import com.cskaoyan.service.FootprintService;
import com.cskaoyan.service.GoodsService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class FootprintServiceImpl implements FootprintService {
    @Autowired
    GoodsService goodsService;
    @Autowired
    MarketFootprintMapper marketFootprintMapper;
    @Override
    public PageData list(Integer userId, Integer page, Integer limit) {
        MarketFootprintExample marketFootprintExample = new MarketFootprintExample();
        //按时间排序
        marketFootprintExample.setOrderByClause("add_time desc");
        marketFootprintExample.createCriteria()
                .andUserIdEqualTo(userId)
                .andDeletedEqualTo(false);
        //开启分页
        PageHelper.startPage(page,limit);
        //查询用户的足迹
        List<MarketFootprint> marketFootprints = marketFootprintMapper.selectByExample(marketFootprintExample);
        //通过用户的足迹查询商品信息，即使浏览重复商品也会显示
        List<Map> list = new ArrayList<Map>();
        for (MarketFootprint marketFootprint : marketFootprints) {
            //通过商品id查询商品信息
            Integer goodsId = marketFootprint.getGoodsId();
            MarketGoods marketGoods =goodsService.findById(goodsId);
            Map<String, Object> map = new HashMap<>();
            map.put("id",marketFootprint.getId());
            map.put("goodsId",marketFootprint.getGoodsId());
            map.put("addTime",marketFootprint.getAddTime());
            map.put("brief",marketGoods.getBrief());
            map.put("name",marketGoods.getName());
            map.put("picUrl",marketGoods.getPicUrl());
            map.put("retailPrice",marketGoods.getRetailPrice());
            list.add(map);
        }

        return PageData.list(list);
    }

    @Override
    public void delete(Integer id) {
        MarketFootprint marketFootprint = new MarketFootprint();
        marketFootprint.setId(id);
        marketFootprint.setDeleted(true);
        //有选择性的进行更新
        int i = marketFootprintMapper.updateByPrimaryKeySelective(marketFootprint);
    }

    @Override
    public int insert(Integer userId, Integer goodsId) {
        //1. 构造插入的对象
        MarketFootprint marketFootprint = MarketFootprint.builder()
                .userId(userId)
                .goodsId(goodsId)
                .addTime(new Date())
                .updateTime(new Date())
                .deleted(false)
                .build();

        //2， 进行插入
        return marketFootprintMapper.insertSelective(marketFootprint);
    }
}
